var datatable;// 定义一个全局的dataTable
String.prototype.replaceAll = function(s1,s2) { 
    return this.replace(new RegExp(s1,"gm"),s2); 
}
$(function() {
	
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			$("#tag").val(0);
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
			$("#tag").val(1);
		}
		
		var nTds = $('td', this);
		var sBrowser = $(nTds[0]).children("input");
		$("#id").val(sBrowser.val());
	});
	
	$("#Error_code").jqxComboBox({promptText: "Select ..."});
	$("#error_code").jqxComboBox({promptText: "Select ...",width: 225,height: 25});
	$("#product_type").jqxComboBox({promptText: "Select ...",width: 225,height: 25});
	initComboboxInterface();
	
	//下载
	$('#file_upload').uploadify({
        'swf'      : '../../static/plugins/uploadify/uploadify.swf',
        'uploader' : '../../kpi/expertDiagnosis/uploadFile',
        'auto'  : false,
        'fileDataName':'file',
        'buttonText' : '选择文件...',
        //'fileTypeExts' : '*.gif; *.jpg; *.png',
        'multi'    : false,
        'method'   :'post',
        'onUploadSuccess' : function(file, data, response) {
        	$("#upload_path").val($("#upload_path").val()+","+data);
        }
    });
	
//	
	if($("#t").val()=="1"){
		$("#Interface").val($("#ppt").val());
		$("#Error_code").val($("#pec").val());
		
		getList();
		
		if($("#table tbody tr").length==1){
			if($("#table tbody tr td").length==1){
				showAddExpertDiagnosis();
			}else{
				showModifyExpertDiagnosis();
			}
		}
	}
})

function getList() {
	var Product_type=$("#Interface").val();
	var Error_code=$("#Error_code").val();
	var Phenomenon_desc=$("#Phenomenon_desc").val();
	
	$("#table tbody tr").remove();
	if (datatable == undefined || datatable == "undefined" || datatable == null) {
	} else {
		datatable.destroy();
	}
	datatable = $('#table').DataTable({
		"aoColumnDefs" : [ {
	        sDefaultContent : '',
	        aTargets : [ '_all' ]
	    } ],
		"bPaginate" : true, // 翻页功能
		"bLengthChange" : false, // 改变每页显示数据数量
		"bFilter" : false, // 过滤功能
		"bSort" : false, // 排序功能
		"bInfo" : true,// 页脚信息
		"bAutoWidth" : true,// 自动宽度
		// "sPaginationType": "full_numbers",//显示分页的样式 还有simple_numbers等
//		"sScrollX" : "100%",
		"sScrollXInner": "110%",
		"iDisplayLength" : 50,
		"bScrollCollapse" : true,
		"oLanguage" : {
			"sLengthMenu" : "每页显示 _MENU_条",
			"sZeroRecords" : "没有找到符合条件的数据",
			"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
			"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
			"sInfoEmpty" : "没有记录",
			"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
			"sSearch" : "搜索：",
			"oPaginate" : {
				"sFirst" : "首页",
				"sPrevious" : "前一页",
				"sNext" : "后一页",
				"sLast" : "尾页"
			}
		},
		"bProcessing" : true,
		"bServerSide" : true,
		"sAjaxSource" : "../../kpi/expertDiagnosis/getAllData",
		"fnServerData" : function(sSource, aoData, fnCallback) {
			$.ajax({
				"type" : "post",
				"contentType" : "application/x-www-form-urlencoded",
				"url" : sSource,
				"async": false,
				"dataType" : "json",
				"data" : {
					"aoData" : JSON.stringify(aoData),
					"Product_type" : Product_type,
					"Error_code" : Error_code,
					"Phenomenon_desc" : Phenomenon_desc
				}, // 以json格式传递
				"success" : function(resp) {
					fnCallback(resp.pageDate);
				}
			});
		},
		columns : [ {
			data : "id",
			render:function(val){
				$("#id").val(val);
				$("#tag").val("1");
				return "<input type='checkbox' name='checkList' value='" + val + "' style='margin-left: 8px;'>";
			}
		}, {
			data : "interface_name"
		}, {
			data : "product_type"
		}, {
			data : "product_type_name"
		}, {
			data : "error_code"
		}, {
			data : "error_code_name"
		}, {
			data : "phenomenon_desc"
		}, {
			data : "cause"
		}, {
			data : "solution"
		}]
	});
}

function reloadTables(){
	var Product_type=$("#Product_type").val();
	var Error_code=$("#Error_code").val();
	var Phenomenon_desc=$("#Phenomenon_desc").val();
	
	$.ajax({
		"type" : "post",
		"contentType" : "application/x-www-form-urlencoded",
		"url" : "../../kpi/expertDiagnosis/getAllData",
		"dataType" : "json",
		"data" : {
			"Product_type" : Product_type,
			"Error_code" : Error_code,
			"Phenomenon_desc" : Phenomenon_desc
		}, // 以json格式传递
		"success" : function(resp) {
			datatable.fnCallback(resp.pageDate);
		}
	});
}

function resetForm(formId){
	$('#'+formId)[0].reset(); 
	var index = $("#Interface").jqxComboBox('getSelectedIndex');
	$("#Interface").jqxComboBox('unselectIndex',index);
}

function showAddExpertDiagnosis(){
	$("#saveBtn").show();
	$("#modBtn").hide();
	$("#controlHideExistEnclosure").hide();
	resetForm("newForm");
	if($("#t").val()=="1" && $("#table tbody tr td").length==1){
		$("#interface").val($("#ppt").val());
		$("#product_type").val($("#pi").val());
		$("#error_code").val($("#pec").val());
		
		$("#Interface").val($("#ppt").val());
		$("#Error_code").val($("#pec").val());
	}else{
		var index = $("#interface").jqxComboBox('getSelectedIndex');
		$("#interface").jqxComboBox('unselectIndex',index);
	}
	layer.open({
		title:'专家诊断新增',
	    type: 1,
	    area: ['600px','480px'],
	    offset: '40px',
	    content:$('#newDiv')
	});
	$("#t").val("0");
}

function addExpertDiagnosis(){
	var param=formToUrl('', 'newForm');
	param=param+"&pt="+$("#product_type").val()+"&ec="+$("#error_code").val()+"&ic="+$("#interface").val();
	$.ajax({
		type : "GET",
		url : "../../kpi/expertDiagnosis/addExpertDiagnosis?"+ param,
		dataType : "json",
		success : function(data) {
			if(data.flag){
				layer.closeAll();
				datatable.ajax.reload();
				layer.alert(data.msgs, {
					icon : 1
				});
			}else{
				layer.alert(data.msgs, {
					icon : 3
				});
			}
		}
	});
}

function showModifyExpertDiagnosis(){
	if($("#tag").val()!=1){
		layer.alert("请选择一条记录！", {
			icon : 0
		});
		return;
	}
	$("#saveBtn").hide();
	$("#modBtn").show();
	$("#existEnclosure").empty();
	$("#controlHideExistEnclosure").show();
	$.ajax({
		type : "POST",
		url : "../../kpi/expertDiagnosis/queryById",
		dataType : "json",
		"data" : {
			"id" : $("#id").val()
		},
		success : function(data) {
			if (data.flag) {
				$("#interface").val(data.result.interface);
				$('#product_type').val(data.result.product_type);
			    $("#error_code").val(data.result.error_code);
				$("#phenomenon_desc").val(data.result.phenomenon_desc);
				$("#cause").val(data.result.cause);
				$("#solution").val(data.result.solution);
				if(data.result.upload_path!=null && data.result.upload_path!=""){
					var path=data.result.upload_path.split(",");
					$.each(path, function(commentIndex, comment) {
						$("#existEnclosure").append("<span>"+comment+"</span><br>");
					});
				}
				
				layer.open({
					title:'专家诊断修改',
				    type: 1,
				    area: ['600px','480px'],
				    offset: '40px',
				    content:$('#newDiv')
				});
			} else {
				layer.alert(data.msgs, {
					icon : 3
				});
			}
		}
	});
}

function modExpertDiagnosis(){
	var param=formToUrl('', 'newForm');
	param=param+"&pt="+$("#product_type").val()+"&ec="+$("#error_code").val()+"&ic="+$("#interface").val();
	$.ajax({
		type : "GET",
		url : "../../kpi/expertDiagnosis/modExpertDiagnosis?"+param,
		dataType : "json",
		success : function(data) {
			if(data.flag){
				layer.closeAll();
				datatable.ajax.reload();
				layer.alert(data.msgs, {
					icon : 1
				});
			}else{
				layer.alert(data.msgs, {
					icon : 3
				});
			}
		}
	});
}

function delExpertDiagnosis(){
	var ids = getChekboxsValues();
	if (ids == null) {
		layer.alert("请至少选择一条记录！", {
			icon : 0
		});
		return;
	}
	
	layer.confirm('确定删除选择的信息吗？', {
		btn : [ '是', '否' ], 
		shade : false
	}, function() {
		$.ajax({
			type : "POST",
			url : "../../kpi/expertDiagnosis/delExpertDiagnosis",
			dataType : "json",
			"data" : {
				"ids" : ids
			},
			success : function(data) {
				if (data.flag) {
					datatable.ajax.reload();
					layer.alert(data.msgs, {
						icon : 1
					});
				} else {
					layer.alert(data.msgs, {
						icon : 3
					});
				}
			}
		});
	}, function() {
	});
}

function checkAll(c){
	if(c.checked){
		$("input[name='checkList']").attr("checked",true);  
	}else{
		$("input[name='checkList']").attr("checked",false);  
	}
}

function getChekboxsValues() {

	var ids = "";
	$('input:checkbox[name=checkList]:checked').each(function(i) {
		ids = ids + $(this).val() + ",";
	});

	if (ids.length == 0) {
		return null;
	} else {
		return ids = ids.substring(0, ids.length - 1);
	}
}

function initComboboxInterface(){
	// prepare the data
    var source =
    {
        datatype: "json",
        datafields: [
            { name: 'value' },
            { name: 'label' }
        ],
        url: "../../kpi/expertDiagnosis/getInterfaceType",
        async: false
    };
    var dataAdapter = new $.jqx.dataAdapter(source);

    // 信令类型名称
    $("#Interface").jqxComboBox(
    { 
    	source: dataAdapter, 
    	promptText: "Select ...",
    	displayMember: "value", 
    	valueMember: "label", 
    	width: 200, 
    	height: 25,
    	autoComplete: true
    });
    
    $("#Interface").on('change', function (event) {
	    initComboboxRender("../../kpi/expertDiagnosis/getResultCode?id="+$(this).val(),"Error_code");
    });
    
    // 信令结果描述码
    $("#interface").jqxComboBox(
    { 
    	source: dataAdapter, 
    	promptText: "Select ...",
    	displayMember: "value", 
    	valueMember: "label", 
    	width: 225, 
    	height: 25,
    	autoComplete: true
    });
    $("#interface").on('change', function (event) {
    	initComboboxRender("../../kpi/expertDiagnosis/getResultCode?id="+$(this).val(),"error_code");
		initComboboxRender("../../kpi/expertDiagnosis/getResultCodeByPT?id="+$(this).val(),"product_type");
    });
}

function showExpertDiagnosis(){
	if($("#tag").val()!=1){
		layer.alert("请选择一条记录！", {
			icon : 0
		});
		return;
	}
	$("#existEnclosure_detail").empty();
	$.ajax({
		type : "POST",
		url : "../../kpi/expertDiagnosis/queryById",
		dataType : "json",
		"data" : {
			"id" : $("#id").val()
		},
		success : function(data) {
			if (data.flag) {
				$("#id_hid").val(data.result.id);
				$("#interface_detail").text(data.result.interface_name);
				$('#product_type_detail').text(data.result.product_type_name);
			    $("#error_code_detail").text(data.result.error_code_name);
				$("#phenomenon_desc_detail").text(data.result.phenomenon_desc);
				$("#cause_detail").text(data.result.cause);
				$("#solution_detail").text(data.result.solution);
				if(data.result.upload_path!=null && data.result.upload_path!=""){
					var path=data.result.upload_path.split(",");
					$.each(path, function(commentIndex, comment) {
						$("#existEnclosure_detail").append("<span>"+comment+"</span>&nbsp;<a href=\"javascript:downFiles('"+comment.replace(/\\/g,'<->')+"');\">附件下载</a> <br>");
					});
				}
				
				layer.open({
					title:'专家诊断查看',
				    type: 1,
				    area: ['600px','480px'],
				    offset: '40px',
				    content:$('#detailDiv')
				});
			} else {
				layer.alert(data.msgs, {
					icon : 3
				});
			}
		}
	});
}

function downFiles(path){
	var url = "../../kpi/expertDiagnosis/downFiles?path="
		+ path;
	window.location.href = url;
}

function initComboboxRender(url,id){
	var source =
    {
        datatype: "json",
        datafields: [
            { name: 'value' },
            { name: 'label' }
        ],
        url: url,
        async: false
    };
    var dataAdapter = new $.jqx.dataAdapter(source);

    // Create a jqxComboBox
    $("#"+id).jqxComboBox(
    { 
    	source: dataAdapter, 
    	promptText: "Select ...",
    	displayMember: "value", 
    	valueMember: "label", 
    	width: 225, 
    	height: 25,
    	autoComplete: true
    });
}